package ucadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryBannerListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryBannerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryBannerListLogic {
	return &QueryBannerListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询banner列表
func (l *QueryBannerListLogic) QueryBannerList(in *pb.QueryBannerConfigListReq) (*pb.QueryBannerConfigListResp, error) {
	defer utils.RecoverPanic()

	var err error
	var list []*usercenter.BannerConfig
	list, err = l.svcCtx.BannerConfigModel.Find(l.ctx, in.State, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var rsp pb.QueryBannerConfigListResp
	rsp.List = make([]*pb.BannerData2, 0)
	if len(list) <= 0 {
		return &rsp, nil
	}

	if in.PageNo <= 1 {
		rsp.Total, err = l.svcCtx.BannerConfigModel.Count(l.ctx, in.State)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}

	for i := 0; i < len(list); i++ {
		rsp.List = append(rsp.List, &pb.BannerData2{
			Id:         list[i].Id,
			BannerName: list[i].BannerName,
			Image:      list[i].BannerImage,
			Url:        list[i].Url,
			PagePath:   list[i].PagePath,
			Order:      list[i].BannerOrder,
			StartTime:  list[i].StartTime.Format(dbkey.DateTimeCNFormat),
			EndTime:    list[i].EndTime.Format(dbkey.DateTimeCNFormat),
			CreateTime: list[i].CreateTime.Format(dbkey.DateTimeCNFormat),
			UpdateTime: list[i].UpdateTime.Format(dbkey.DateTimeCNFormat),
			State:      list[i].State,
		})
	}

	return &rsp, nil
}
